<template>
  <Box v-if="data.show" style="margin-top: 60px">
    <a-collapse v-model:activeKey="activeKey" ghost expandIconPosition="right">
      <a-collapse-panel key="1" :header="t('数据配置')">
        <BasicTable @register="registerTable" class="BannerDrag">
          <template #bodyCell="{ column, text, record, index }">
            <template v-if="['index', 'url'].includes(column.dataIndex)">
              <Icon
                class="mover"
                icon="ant-design:drag-outlined"
                v-if="column.dataIndex == 'index'"
              />
              <div v-if="column.dataIndex == 'url'">
                <a-input
                  readonly
                  v-model:value="record[column.dataIndex]"
                  style="width: 176px; border: none"
                />
                <a-upload
                  action=""
                  :customRequest="submitUpload"
                  accept=""
                  :max-count="1"
                  :show-upload-list="false"
                >
                  <Icon
                    icon="ant-design:cloud-upload-outlined"
                    @click="
                      () => {
                        colIndex = index;
                      }
                    "
                  />
                </a-upload>
              </div>
            </template>
            <template v-else-if="column.dataIndex == 'action'">
              <TableAction
                :actions="[
                  {
                    icon: 'ant-design:delete-outlined',
                    color: 'error',
                    title: t('删除'),
                    popConfirm: {
                      title: t('是否确认删除'),
                      confirm: handleDelete.bind(null, index),
                    },
                  },
                ]"
              />
            </template>
            <template v-else> {{ text }} </template>
          </template>
        </BasicTable>
        <div class="ml-5px">
          <a-button @click="handleCreate" class="w-full mb-6">
            <plus-outlined />{{ t('新增（最大不超过8张图片）') }}
          </a-button>
        </div>
      </a-collapse-panel>
      <a-collapse-panel key="2" :header="t('大小定位')">
        <Location v-model:info="data.info.h" />
      </a-collapse-panel>
    </a-collapse>
  </Box>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref, watch, nextTick } from 'vue';
  import Box from './Box.vue';
  import Sortable from 'sortablejs';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { bannerInfo } from '../config/info';
  import { Icon } from '/@/components/Icon';
  import { BannerInfo, bannerItem } from '/@/model/mobileDesign/designer';
  import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table';
  import Location from './collapse/Location.vue';
  import { getAppEnvConfig } from '/@/utils/env';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useUserStore } from '/@/store/modules/user';
  import { isNullAndUnDef } from '/@/utils/is';

  const { t } = useI18n();
  const props = withDefaults(
    defineProps<{
      info: BannerInfo;
    }>(),
    {
      info: () => {
        return bannerInfo;
      },
    },
  );
  const activeKey = ref(['1', '2']);
  const data: {
    show: boolean;
    info: BannerInfo;
  } = reactive({
    show: false,
    info: bannerInfo,
  });
  const tableData = ref<bannerItem[]>([]);
  const colIndex = ref();
  const userStore = useUserStore();
  watch(
    () => props.info,
    (val) => {
      if (val) data.info = val;
    },
    {
      deep: true,
    },
  );

  const columns: BasicColumn[] = [
    {
      title: t('排序'),
      dataIndex: 'index',
      width: 40,
    },
    {
      title: t('上传图片'),
      dataIndex: 'url',
      width: 160,
    },
  ];
  const [registerTable, { getDataSource, setTableData }] = useTable({
    title: '',
    dataSource: tableData.value,
    columns,
    pagination: false,
    striped: false,
    useSearchForm: false,
    bordered: true,
    showIndexColumn: false,
    canResize: false,
    actionColumn: {
      width: 40,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    },
  });
  onMounted(() => {
    data.info = props.info;
    nextTick(() => {
      setTableData(data.info.config.imgs);
    });
    data.show = true;
  });
  watch(
    () => tableData.value,
    (val) => {
      if (val && val.length) {
        nextTick(() => {
          const tbody: any = document.querySelector('.BannerDrag .ant-table-tbody');
          const tr: any = tbody.querySelector('tr.ant-table-row[draggable="false"]');
          if (tr) tr.remove();
          Sortable.create(tbody, {
            handle: '.mover',

            onEnd: (evt) => {
              const { oldIndex, newIndex } = evt;
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || oldIndex === newIndex) {
                return;
              }

              let columns: bannerItem[] = getDataSource();

              setTableData([]);

              tableData.value = [];
              nextTick(() => {
                let old = columns[oldIndex - 1];
                columns.splice(oldIndex - 1, 1);
                columns.splice(newIndex - 1, 0, old);
                columns.forEach((o, i) => {
                  o.index = i + 1;
                });
                tableData.value = columns;
                setTableData(tableData.value);
              });
            },
          });
        });
        resetDisplay();
      }
    },
    {
      deep: true,
    },
  );
  function handleCreate() {
    let dataSource: bannerItem[] = getDataSource();
    if (dataSource.length >= 8) return;
    let obj = {
      index: dataSource.length,
      url: null,
    };
    dataSource.push(obj);
    tableData.value = dataSource;
    resetDisplay();
  }
  function handleDelete(index) {
    tableData.value.splice(index, 1);
  }

  function resetDisplay() {
    data.info.config.imgs = tableData.value;
  }

  const submitUpload = (file) => {
    let action = getAppEnvConfig().VITE_GLOB_API_URL + '/system/file';
    const formData = new FormData();
    formData.append('file', file.file);
    formData.append('remark', '上传');
    const xhr = new XMLHttpRequest();
    xhr.open('post', action, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userStore.getToken);
    xhr.onload = () => {
      const response = JSON.parse(xhr.response);
      let dataSource: bannerItem[] = getDataSource();
      dataSource[colIndex.value].url = response.data;

      tableData.value = dataSource;
    };
    xhr.onerror = () => {
      console.log(t('上传失败'));
    };
    xhr.ontimeout = function timeout() {
      console.log(t('上传超时'));
    };
    xhr.send(formData);
  };
</script>

<style lang="less" scoped>
  :deep(.ant-form-item-control) {
    overflow: auto;
  }

  .vben-basic-table.BannerDrag {
    margin: 0 -20px;
    max-width: calc(100% + 40px);
  }
</style>
